<template>
    <div class="plr20">
        <div class="p20 table-striped">
            <el-button
                class="pb20"
                type="primary"
                icon="el-icon-plus"
                size="mini"
                v-hasPermi="['system:post:add']"
                @click="showAddDialog"
                >新增</el-button
            >
            <div>
                <el-table :data="list">
                    <!-- <el-table-column
                        type="selection"
                        width="55"
                        align="center"
                    /> -->
                    <el-table-column
                        label="工种类型"
                        align="center"
                        prop="workType"
                    />
                    <el-table-column
                        label="工资卡号"
                        align="center"
                        prop="bankCard"
                    />
                    <el-table-column
                        label="合同编号"
                        align="center"
                        prop="contractnNo"
                    />
                    <el-table-column
                        label="体检情况"
                        align="center"
                        prop="checkup"
                    />
                    <el-table-column
                        label="所属单位"
                        align="center"
                        prop="companyName"
                    />
                    <el-table-column
                        label="入场时间"
                        align="center"
                        prop="indate"
                        width="180"
                    >
                    </el-table-column>
                    <el-table-column
                        label="操作"
                        align="center"
                        class-name="small-padding fixed-width"
                    >
                        <template slot-scope="scope">
                            <el-button
                                size="mini"
                                type="text"
                                icon="el-icon-edit"
                                @click="handleUpdate(scope.row)"
                                v-hasPermi="['system:post:edit']"
                                >编辑</el-button
                            >
                            <el-button
                                size="mini"
                                type="text"
                                icon="el-icon-delete"
                                @click="deleteUserPost(scope.row.postId)"
                                v-hasPermi="['system:post:remove']"
                                >删除</el-button
                            >
                        </template>
                    </el-table-column>
                </el-table>
                <pagination
                    v-show="total > 0"
                    :total="total"
                    :page.sync="pageNum"
                    :limit.sync="pageSize"
                    @pagination="getUserPost"
                />
            </div>
        </div>
        <el-dialog
            :before-close="closeDialog"
            :title="title"
            :visible.sync="open"
            width="630px"
            height="60%"
            append-to-body
            class="my-el-dialog"
        >
            <el-form
                ref="ruleForm"
                :model="form"
                :rules="rules"
                label-width="80px"
            >
                <el-form-item label="工种类型" prop="workType">
                    <el-select v-model="form.workType" style="width:100%;">
                        <el-option
                            v-for="dict in workTypeOptions"
                            :key="dict.dictValue"
                            :label="dict.dictLabel"
                            :value="dict.dictValue"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="工资卡号">
                    <el-input
                        v-model="form.bankCard"
                        placeholder="请输入工资卡号"
                    />
                </el-form-item>
                <el-form-item label="合同编号">
                    <el-input
                        v-model="form.contractnNo"
                        placeholder="请输入合同编号"
                    />
                </el-form-item>
                <el-form-item label="合同照片">
                    <el-upload
                        class="avatar-uploader"
                        ref="upload1"
                        :limit="limitImgNumber"
                        list-type="picture-card"
                        :file-list="fileList"
                        accept=".png, .jpg"
                        :headers="upload.headers"
                        :action="upload.url"
                        :on-remove="removeFile1"
                        :on-change="handleFileChange1"
                        :on-success="handleFileSuccess1"
                        :class="{ hideAdd: uploadDisabled1 }"
                    >
                        <i class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="体检情况">
                    <el-select v-model="form.checkup" style="width:100%;">
                        <el-option
                            v-for="dict in checkupOptions"
                            :key="dict.dictValue"
                            :label="dict.dictLabel"
                            :value="dict.dictValue"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item
                    label="体检照片"
                    v-show="form.checkup == 1 || form.checkup == '合格'"
                >
                    <el-upload
                        class="avatar-uploader"
                        ref="upload2"
                        :limit="limitImgNumber1"
                        :file-list="fileList1"
                        list-type="picture-card"
                        accept=".png, .jpg"
                        :headers="upload.headers"
                        :action="upload.url"
                        :disabled="upload.isUploading"
                        :on-remove="removeFile2"
                        :on-success="handleFileSuccess2"
                        :on-change="handleFileChange2"
                        :class="{ hideAdd: uploadDisabled2 }"
                    >
                        <i class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="所属公司" prop="companyName">
                    <el-input
                        v-model="form.companyName"
                        placeholder="请输入所属公司"
                    />
                </el-form-item>
                <el-form-item label="入场时间" prop="indate">
                    <el-date-picker
                        style="width:100%;"
                        value-format="yyyy-MM-dd"
                        type="date"
                        v-model="form.indate"
                    ></el-date-picker>
                </el-form-item>
                <el-form-item label="离场时间">
                    <el-date-picker
                        style="width:100%;"
                        value-format="yyyy-MM-dd"
                        type="date"
                        v-model="form.leavedate"
                    ></el-date-picker>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm('ruleForm')"
                    >确 定</el-button
                >
                <el-button @click="closeDialog('close')">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import { getToken } from "@/utils/auth";
import { userPost, addUserPost, deleteUserPost, modifiUserPost } from '@/api/users'
export default {
    name: 'workExperience',
    data () {
        return {
            uploadDisabled1: false,
            uploadDisabled2: false,
            limitImgNumber: 3,
            limitImgNumber1: 3,
            // 用户导入参数
            upload: {
                // 设置上传的请求头部
                headers: { Authorization: "Bearer " + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + "/common/upload",
            },
            title: '添加从业经历',
            open: false,
            form: {
                userId: '',
                workType: '',
                bankCard: '',
                contractnNo: '',
                contracts: [],
                checkup: '',
                healths: [],
                companyName: '',
                indate: '',
                leavedate: ''
            },
            fileList: [],
            fileList1: [],
            rules: {
                workType: [
                    { required: true, message: "请选择工种", trigger: "blur" },
                ],
                companyName: [
                    { required: true, message: "请输入单位名称", trigger: "blur" }
                ],
                indate: [
                    { required: true, message: "请选择入场时间", trigger: "blur" }
                ]
            },
            workTypeOptions: [],
            checkupOptions: [],
            imageUrl: '',
            list: [],
            pageNum: 1,
            pageSize: 10,
            total: 0,
            isAddUserPost: true // 是新增还是修改
        }
    },
    created () {
        this.getUserPost()
        this.getDicts("work_type").then(response => {
            this.workTypeOptions = response.data;
        });
        this.getDicts("checkup").then(response => {
            this.checkupOptions = response.data;
        });
        this.form.userId = this.$route.params.id
    },
    methods: {
        handleFileChange1 (file, fileList) {
            this.uploadDisabled1 = fileList.length >= this.limitImgNumber;
        },
        handleFileChange2 (file, fileList) {
            this.uploadDisabled2 = fileList.length >= this.limitImgNumber1;
        },
        closeDialog (done) {
            this.$refs.upload1.clearFiles();
            this.$refs.upload2.clearFiles();
            done && done != 'close' ? done() : this.open = false
        },
        showAddDialog () {
          this.uploadDisabled2=false;
          this.uploadDisabled1=false;
            this.title = "添加从业经历";
            this.open = true;
            this.isAddUserPost = true;
            this.form = {
                userId: this.$route.params.id,
                workType: '',
                bankCard: '',
                contractnNo: '',
                contracts: [],
                checkup: '',
                healths: [],
                companyName: '',
                indate: '',
                leavedate: ''
            };
            this.fileList = [];
            this.fileList1 = [];
        },
        handleUpdate (row) {
            this.title = "编辑从业经历";
            this.open = true;
            this.isAddUserPost = false;
            this.form = Object.assign(this.form, row);
            this.form.contracts=[];
            this.form.healths=[];
            this.fileList = [];
            this.fileList1 = [];
            if (row.contractPhotos !=null && row.contractPhotos[0] !=null){
              row.contractPhotos.forEach(item => {
                this.fileList.push({
                  url: item.attaPath
                });
                this.form.contracts.push(item.attaPath);
              });
            } else {
                this.fileList = [];
            }
          if (row.healthPhotos !=null && row.healthPhotos[0] !=null){
            row.healthPhotos.forEach(item => {
              this.fileList1.push({
                url: item.attaPath
              });
              this.form.healths.push(item.attaPath);
            });
          } else {
            this.fileList1 = [];
          }
          this.uploadDisabled1 = this.fileList.length >= this.limitImgNumber;
          this.uploadDisabled2 = this.fileList1.length >= this.limitImgNumber1;
        },
        workTypeFormatter (item) {
            for (let i = 0; i < this.workTypeOptions.length; i++) {
                if (item.workType == this.workTypeOptions[i].dictLabel) {
                    return this.workTypeOptions[i].dictValue
                }
            }
            return item.workType
        },
        checkupFormatter (item) {
            for (let i = 0; i < this.checkupOptions.length; i++) {
                if (item.checkup == this.checkupOptions[i].dictLabel) {
                    return this.checkupOptions[i].dictValue
                }
            }
            return item.checkup
        },
        async getUserPost () {
            let res = await userPost({ userId: this.$route.params.id })
            if (res.code == 200) {
                this.list = res.rows
                this.total = res.total
            }
        },
        removeFile1 (file, fileList) {
            this.form.contracts = [];
            fileList.forEach(item => {
                let url = item.response ? item.response.url : item.url
                this.form.contracts.push(url);
            });
            setTimeout(() => {
                this.handleFileChange1(file, fileList)
            }, 500)
        },
        // 文件上传成功处理
        handleFileSuccess1 (response, file, fileList) {
            this.form.contracts = [];
            fileList.forEach(item => {
                let url = item.response ? item.response.url : item.url;
               this.form.contracts.push(url);
            });
        },
        removeFile2 (file, fileList) {
            this.form.healths = [];
            fileList.forEach(item => {
                let url = item.response ? item.response.url : item.url;
                this.form.healths.push(url);
            });
            setTimeout(() => {
                this.handleFileChange2(file, fileList)
            }, 500)
        },
        // 文件上传成功处理
        handleFileSuccess2 (response, file, fileList) {
            this.form.healths = [];
            fileList.forEach(item => {
                let url = item.response ? item.response.url : item.url;
              this.form.healths.push(url);
            });
        },
        submitForm (formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (this.isAddUserPost) {
                        this.addUserPost()
                    } else {
                        this.modifiUserPost()
                    }
                } else {
                    return false;
                }
            });
        },
        async addUserPost () {
            let res = await addUserPost(this.form)
            if (res.code == 200) {
                this.fileList = []
                this.$refs.upload1.clearFiles()
                this.$refs.upload2.clearFiles()
                this.open = false
                this.$message({
                    message: '新增成功',
                    type: 'success'
                })
                this.getUserPost()
            }
        },
        async deleteUserPost (id) {
            let res = await deleteUserPost(id)
            if (res.code == 200) {
                this.$message({
                    message: '删除成功',
                    type: 'success'
                })
                this.getUserPost()
            }
        },
        async modifiUserPost () {
            this.form.workType = this.workTypeFormatter(this.form);
            this.form.checkup = this.checkupFormatter(this.form);
          if (this.form.contracts === ""){
            this.form.contracts=[];
          }
          if (this.form.healths === ""){
            this.form.healths=[];
          }
          this.form.contractPhotos=null;
          this.form.healthPhotos=null;
            let res = await modifiUserPost(this.form);
          if (res.code == 200) {
                this.fileList = []
                this.$refs.upload1.clearFiles()
                this.$refs.upload2.clearFiles()
                this.open = false
                this.$message({
                    message: '修改成功',
                    type: 'success'
                })
                this.getUserPost()
            }
        }
    }
}
</script>
<style scoped>
.plr20 {
    padding: 0 20px;
}
.p20 {
    padding: 20px;
}
.pb20 {
    margin-bottom: 20px;
}
.table-striped {
    width: 100%;
    background: #fff;
    border-radius: 6px;
    margin-top: 10px;
    padding-top: 5px;
    padding-bottom: 13px;
    box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.2);
}
</style>
<style>
.my-el-dialog .el-dialog__body {
    height: 500px;
    overflow: scroll;
}
</style>
